package com.example.exception;

import com.example.common.AppResult;
import com.example.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Created with IntelliJ IDEA.
 * Description:统一异常处理
 * User: bjc
 * Date: 2025-09-03
 * Time: 11:13
 */
@Slf4j
@RestControllerAdvice //表示全局异常处理,是由@ControllerAdvice+@ResponseBody合成
public class GlobalExceptionHandler {
    /**
     * 处理自定义的已知异常
     * @param e
     * @return
     */
    @ExceptionHandler(ApplicationException.class)
    public AppResult handlerApplicationException(ApplicationException e){
        //打印异常信息
        e.printStackTrace();
        //记录日志
        log.error(e.getMessage());
        //获取异常信息
        if(e.getErrResult() != null){
            //返回自定义异常类中记录的异常状态
            return e.getErrResult();
        }
        //返回默认异常状态
        return AppResult.failed(e.getMessage());
    }

    /**
     * 处理未被捕获的其他异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public AppResult handlerException(Exception e){
        //打印异常
        e.printStackTrace();
        //记录日志
        log.error(e.getMessage());
        //获取异常信息
        if(e.getMessage() == null || e.getMessage().equals("")){
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        return AppResult.failed(e.getMessage());
    }
}
